
###############################################################################
# Name:         log
# Usage:        from mylib import log
#               logger = log.make_logger(__file__)
#               # logger.setLevel(log.INFO)
# Author:       Bright Li
# Modified by:
# Created:      2019-03-05
# Version:      [0.1.4]
# RCS-ID:       $$
# Copyright:    (c) Bright Li
# Licence:
###############################################################################

import logging
import os.path
import inspect

try:
    from .glob import GlobMnger
    LOGGER_KEYNAME = "LOGGER_LEVEL"
    if not GlobMnger.check(LOGGER_KEYNAME):
        # GlobMnger._listAll()
        GlobMnger.register(LOGGER_KEYNAME, logging.WARNING)
except ImportError:
    pass

NOTSET, DEBUG, INFO, WARNING, ERROR, CRITICAL = range(0, 51, 10)


def get_module_rpath(abspath=None):
    # from pprint import pprint
    # pprint(inspect.stack())

    if not abspath:
        abspath = inspect.stack()[3][1]

    # file_name = os.path.basename(abspath)
    rpath = os.path.relpath(abspath)  # 相对路径
    module_name, _ = os.path.splitext(rpath)

    return module_name


def detail(func):
    def wrapper(this, msg, *args, **kwargs):
        caller = inspect.stack()[1][3]

        msg = "[{}::{}()] ---- {}".format(this.logger.name, caller, msg)
        return func(this, msg, *args, **kwargs)
    return wrapper


class MycLogger:
    """ 延迟设定logger对象的level """
    def __init__(self):
        # self.logger
        self.first_run = True
        self.level = None

    def create_logger(self, name, level=None, output_file=None):
        if output_file is None:
            handler = logging.StreamHandler()
        else:
            handler = logging.FileHandler(output_file)
        # handler.setLevel(level)
        if output_file:
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        else:
            # formatter = logging.Formatter('---- [%(name)s] %(levelname)s ----  %(message)s')
            formatter = logging.Formatter('---- %(levelname)s %(message)s')
        handler.setFormatter(formatter)

        name = get_module_rpath(name)
        self.logger = logging.getLogger(name)

        self.logger.addHandler(handler)

    def setLevel(self, level):
        """ 手动修改level的调用接口 """
        self.level = level

    def _check_level(self):
        if not self.first_run:  return
        if not self.level:
            self.level = GlobMnger.get("LOGGER_LEVEL")
        self.logger.setLevel(self.level)

    @detail
    def debug(self, msg, *args, **kwargs):
        self._check_level()
        self.logger.debug(msg, *args, **kwargs)

    @detail
    def info(self, msg, *args, **kwargs):
        self._check_level()
        self.logger.info(msg, *args, **kwargs)

    @detail
    def warn(self, msg, *args, **kwargs):
        self._check_level()
        self.logger.warning(msg, *args, **kwargs)

    @detail
    def error(self, msg, *args, **kwargs):
        self._check_level()
        self.logger.error(msg, *args, **kwargs)

    @detail
    def critical(self, msg, *args, **kwargs):
        self._check_level()
        self.logger.critical(msg, *args, **kwargs)


def make_logger(name=None, level=None, output_file=None):
    """ return a object of logger_info """
    myc_logger = MycLogger()
    myc_logger.create_logger(name, level, output_file)
    return myc_logger


if __name__ == "__main__":
    class T:
        @classmethod
        def test(cls):
            logger = make_logger(__file__)
            # logger.debug("Hello, Logger!")
            logger.setLevel(10)
            logger.debug("See you again, Logger!")

    T.test()
